<?php
namespace Admin\Controller;
use Common\Controller\CoreController;
class GoodsController extends CoreController {//商品页面
	public function index(){//商品列表
		$this->addGoods=U('addGoods');
		$this->assign('text','添加商品');
		$user=M('goods');
		$this->goodslist=$user->select();//从数据库保存取出，在index页面显示；OK
		$this->assign('edit',U('editGoods'));
		$this->assign('del',U('delGoods'));
		// $User = M('User'); 
		// 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
		if(isset($_GET['p'])){
			$goodslist = $user->where('status=1')->order('id')->page($_GET['p'].',5')->select();
			$this->assign('goodslist',$goodslist);// 赋值数据集
			$count  = $user->where('status=1')->count();// 查询满足要求的总记录数
			$Page   = new \Think\Page($count,5);// 实例化分页类 传入总记录数和每页显示的记录数
			$show    = $Page->show();// 分页显示输出
			$this->assign('page',$show);// 赋值分页输出
		}else{
			$_GET['p']=1;
			// $page=I('get.p');
			// $page=1;
			$goodslist = $user->where('status=1')->order('id')->page($_GET['p'].',5')->select();
			$this->assign('goodslist',$goodslist);// 赋值数据集
			$count  = $user->where('status=1')->count();// 查询满足要求的总记录数
			$Page   = new \Think\Page($count,5);// 实例化分页类 传入总记录数和每页显示的记录数
			$show    = $Page->show();// 分页显示输出
			$this->assign('page',$show);// 赋值分页输出
		}
		
		$this->display(); // 输出模板

		// $this->display();

	}

	public function addGoods(){//商品列表
		// $cate=M('category')->select();
		$this->optionstr=$this->getCateOptionHtml();
		if(IS_POST){
			$goodsname=I('post.goodsname');//获取商品名字，判断是否和数据库已经有
			$numgoods=I('post.numgoods');
			$keyword=I('post.keyword');
			$description=I('post.description');
			$stock=I('post.stock');
			$price=I('post.price');
			$details=I('post.details');
			$status=I('post.status');
			// $banner=I("post.category");
			// var_dump($banner);
			// exit;
			if(empty($goodsname)&&empty($numgoods)&&empty($keyword)&&empty($description)&&empty($stock)&&empty($price)&&empty($details)){
				// echo 1;
				$this->error('请输入完整的商品信息','addGoods');
			}

		
			
			$user=M('goods');
			$data=array(//插入商品表信息表
				'goodsname'=>I('post.goodsname'),
				'numgoods'=>I('post.numgoods'),
				'keyword'=>I('post.keyword'),
				'description'=>I('post.description'),
				'stock'=>I('post.stock'),
				'price'=>I('post.price'),
				'details'=>I('post.details'),
				'status'=>I('post.status'),
				'add_time'=>date('Y-m-d H:i:s',time())
				);
			// print_r($data);OK
			$r=$user->where("goodsname='{$goodsname}'")->find();
			// print_r($r);//OK
			if(empty($r)){
				$goodsid=M('goods')->add($data);//获取商品的ID
				// echo $goodsid;
				// exit;//此处经常出错必须设施idwe为primary key 要不然经常是1
				if(!is_null($goodsid)&&$goodsid>0){
					// header('Location:'.U('index'));
					$gtc=M('goods_category');
					$cate=I("post.category");//调剂表单获取的多个分列选项的value值
					// var_dump($cate);
					// exit;				
					foreach ($cate as $key => $value) {
						$data['goods_id']=$goodsid;
						$data['category_id']=$value;
						$r=$gtc->add($data);
					}
					// exit;
						if($r){
							$photo=M('photo');
							for ($i=0; $i <count(I('post.banner')) ; $i++) { 
								$data=array(//插入商品照片表与之对应的商品ID相对应
									'goods_id'=>$goodsid,
									'name'=>I('post.banner')[$i],
									'title'=>I('post.title')[$i],
									'link'=>I('post.link')[$i],
									'alt'=>I('post.alt')[$i],

									'add_time'=>date('Y-m-d H:i:s',time()+8*3600)
									);
									if($photo->add($data)){
										header("location:index");
									}else{
										$this->error('操作失败');
									}
							}
						}else{
							$this->error('操作失败');
						}
					
				}else{
					$this->error('保存失败','addGoods');
				}

			}else{
				$this->error('该商品已存在','addGoods');
			}

		}else{
			$this->action=U('addGoods');
			$this->cancle=U('index');
	        $this->display();
		}
	}

	public function editGoods(){//商品编辑
		if($_GET['id']){
			$this->action=U('editSave');
			$id=$_GET['id'];//获得商品的ID，从数据库找出对应商品的所有信息，在进行重新编辑
			$user=M('goods');
			$goodslist=$user->where("id='{$id}'")->find();//OK
			$this->assign('goodslist',$goodslist);
			$result=M('goods_category');
			$r=$result->where("goods_id='{$id}'")->select();
			foreach ($r as $key => $value) {
				$cate[]=$value['category_id'];
			}
			$this->optionstr=$this->getCateOptionHtml($cate);
			$u=M('photo');
			$banner=$u->where("goods_id='{$id}'")->select();
			//成功获取到每个商品ID相对应的照片里的与之对应的所有照片
			// print_r($banner);
			// exit;
			$this->assign('banner',$banner);
			$this->display();
		}
	}

	public function editSave(){//负责处理编辑后的数据。新数据保存到数据库
		header('Content-type:text/html;charset=utf-8');
		if(IS_POST){


		if(!is_null(I('post.saveid'))){
			$id=I('post.saveid');
			$data=array(
				'goodsname'=>I('post.goodsname'),
				'numgoods'=>I('post.numgoods'),
				'keyword'=>I('post.keyword'),
				'description'=>I('post.description'),
				'stock'=>I('post.stock'),
				'price'=>I('post.price'),
				'details'=>I('post.details'),
				'status'=>I('post.status'),
				'add_time'=>date('Y-m-d H:i:s',time())
					);
				// print_r($data);
				// exit;
				$user=M('goods');
				$r=$user->where("id='{$id}'")->save($data);
				// exit;
				if($r){//商品信息确定更新成功；在进行goods_category表的
					$gtc=M('goods_category');
					$del=$gtc->where("goods_id='{$id}'")->delete();
					if($del){
						$cate=I("post.category");//调剂表单获取的多个分列选项的value值
							foreach ($cate as $key => $value) {
								$d['goods_id']=$id;
								$d['category_id']=$value;
								$r=$gtc->add($d);
								}
						if($r){
								$photo=M('photo');
								$del=$photo->where("goods_id='{$id}'")->delete();//OK
								for ($i=0; $i <count(I('post.banner')) ; $i++) { 
									$d=array(//插入商品照片表与之对应的商品ID相对应
										'goods_id'=>$id,
										'name'=>I('post.banner')[$i],
										'title'=>I('post.title')[$i],
										'link'=>I('post.link')[$i],
										'alt'=>I('post.alt')[$i],
										'add_time'=>date('Y-m-d H:i:s',time()+8*3600)
										);
										if($photo->add($d)){
											header("location:index");
										}else{
											$this->error('操作失败');
										}
									}
								
							}else{
								$this->error('操作失败');
							}
					}else{
						$this->error('操作失败');
					}
					
				}else{
					$this->error('更新失败','index');
				}		
		}else{
			$this->error('操作失败');
		}
	}
	}

	public function delGoods(){
		if(!is_null(I('get.delid'))){
			$delid=I('get.delid');
			$user=M('goods');
			$r=$user->where("id='{$delid}'")->delete();
			$u=M('goods_category');
			$r=$u->where("goods_id='{$delid}'")->delete();
			
			header("location:index");
			
		}
	}


public function getCateByPid ($pid=0){
		// global $mysql;
		// $sql ="SELECT * FROM category WHERE status=1 and pid={$pid}";
		// $result = $mysql->getAll($sql);
		$user=M('Category');
		$result=$user->where("status=1 and precategory={$pid}")->select();
		if(!empty($result)){
			foreach ($result as $key => $value) {
				$result[$key]['child']=$this->getCateByPid($value['id']);
			}
		}
		return $result;
    }


		public function getCateOptionHtml($selectId=0,$cate=array()){
		static $optionStr;
		if(empty($cate)){
		$cate = $this->getCateByPid(0);
		}
		foreach ($cate as $key => $value) {
		if(is_array($selectId)){
		if(in_array($value['id'],$selectId)){
		$optionStr = $optionStr.'<option value="'.$value['id'].'" selected="selected">';
		}else{
		$optionStr = $optionStr.'<option value="'.$value['id'].'">';
		}
		}else{
		if($selectId==$value['id']){
		$optionStr = $optionStr.'<option value="'.$value['id'].'" selected="selected">';
		}else{
		$optionStr = $optionStr.'<option value="'.$value['id'].'">';
		}
		}

		for ($i=1; $i <$value['level'] ; $i++) { 
		$optionStr = $optionStr.'&nbsp;&nbsp;&nbsp;';
		}
		if($value['level']==0){
		$optionStr = $optionStr.$value['catename'].'</option>';
		}else{
		$optionStr = $optionStr.'└─'.$value['catename'].'</option>';
		}

		if(!empty($value['child'])){
		$this->getCateOptionHtml($selectId,$value['child']);
		}

		}
		return $optionStr;
	}




}